<template>
  <div class="container">
    <!-- 查询条件表单 -->
    <div class="query-form">
      <a-form ref="formRef" :model="queryForm" label-align="left" auto-label-width>
        <a-row justify="start" :gutter="16">
          <a-col :span="6">
            <a-form-item field="businessKey" :label="$t('workflow.processInstance.columns.businessKey')">
              <a-input v-model="queryForm.businessKey"
                :placeholder="$t('common.inputPlaceholder') + $t('workflow.processInstance.columns.businessKey')" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="processDefinitionKey" :label="$t('workflow.processInstance.columns.processDefinition')">
              <a-select v-model:value="queryForm.processDefinitionKey" allow-clear allow-search
                :placeholder="$t('common.inputPlaceholder') + $t('workflow.processInstance.columns.processDefinition')"
                :defaultActiveFirstOption="false" :options="options" @search="handleSearch" @focus="handleFocus"
                @change="handleChange">
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div>
        <!-- 查询按钮 -->
        <a-button-group>
          <a-button type="primary" @click="search">{{ t('common.search') }}</a-button>
          <a-button @click="clear">{{ t('common.clear') }}</a-button>
        </a-button-group>
      </div>
    </div>

    <!-- 表格 -->
    <a-table row-key="id" :data="tableData" :loading="loading" :pagination="pagination" :row-selection="rowSelection"
      @page-change="onPageChange" @selection-change="onSelectionChange">
      <template #columns>
        <a-table-column :title="$t('workflow.processInstance.columns.id')" data-index="id" />
        <a-table-column :title="$t('workflow.processInstance.columns.businessKey')" data-index="businessKey" />
        <a-table-column :title="$t('workflow.processInstance.columns.processDefinition')"
          data-index="processDefinition">
          <template #cell="{ record }">
            {{ record.processDefinition.name }}
          </template>
        </a-table-column>
        <a-table-column :title="$t('workflow.processDefinition.columns.version')" data-index="version">
          <template #cell="{ record }">
            {{ record.processDefinition.version }}
          </template>
        </a-table-column>
        <a-table-column :title="$t('common.status')" data-index="suspensionState">
          <template #cell="{ record }">
            <a-tag :color="record.suspensionState === 1 ? 'green' : 'grey'">{{
              record.suspensionState === 1 ?
                t('workflow.processInstance.columns.activate') :
                t('workflow.processInstance.columns.suspend') }}</a-tag>
          </template>
        </a-table-column>
        <a-table-column :title="$t('common.optional')" align="center" fixed="right">
          <template #cell="{ record }">
            <a-space>
              <a-button type="text" v-if="record.suspensionState == 2" size="small"
                :title="$t('workflow.processInstance.actions.activate')" @click="handleActive(record)">
                <icon-caret-right />
              </a-button>
              <a-button type="text" v-if="record.suspensionState == 1" size="small"
                :title="$t('workflow.processInstance.actions.suspend')" @click="handleSuspend(record)">
                <icon-pause />
              </a-button>
              <a-button type="text" size="small" @click="handleView(record)">
                <icon-eye />
              </a-button>
              <a-popconfirm :content="$t('common.deleteTip')" @ok="handleDelete(record)">
                <a-button type="text" size="small" status="danger">
                  <icon-delete />
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table-column>
      </template>
      <template #footer>
        <div class="table-footer">
          <a-button-group>
            <a-button type="primary" @click="openEditModal()">
              <template #icon>
                <icon-plus />
              </template>
              {{ t('common.add') }}</a-button>
            <!-- <a-upload accept=".bpmn,.xml" :custom-request="handleUpload">
              <template #upload-button>
                <a-button type="primary">
                  <template #icon><icon-upload /></template>
                  {{ $t('common.importFile') }}
                </a-button>
              </template>
            </a-upload> -->
            <a-popconfirm :content="$t('common.deleteTip')" @ok="handleBatchDelete">
              <a-button status="danger" :disabled="selectedKeys.length === 0">
                <template #icon><icon-delete /></template>
                {{ $t('common.batchDelete') }}
              </a-button>
            </a-popconfirm>
          </a-button-group>
        </div>
      </template>
    </a-table>

    <!-- 流程图查看弹窗 -->
    <a-modal v-model:visible="previewVisible" :title="`流程实例实时流程图`" :mask-closable="true" width="1200px"
      @before-close="data = null">
      <BpmnModeler ref="bpmnViewer" :xmlStr="data" :versionTag="versionTag" :highlightActiveNodes="highlightActiveNodes"
        style="height: 60vh;" />
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import { processInstanceApi, processDefinitionApi } from '@/api/workflow';
import BpmnModeler from '@/components/bpmn/BpmnModeler.vue';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const loading = ref(false);
const setLoading = (value) => {
  loading.value = value;
};

// 查询表单
const formRef = ref();
const data = ref(null);
const versionTag = ref(null);
const highlightActiveNodes = ref([]);
const options = ref([]);
const queryForm = reactive({
  businessKey: '',
  processDefinitionKey: '',
});

// 表格数据
const tableData = ref([]);
const selectedKeys = ref([]);

// 分页配置
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
});

// 表格选择配置
const rowSelection = {
  type: 'checkbox',
  showCheckedAll: true,
};

// 预览相关
const previewVisible = ref(false);
const bpmnViewer = ref();

const handleFocus = () => {
  handleSearch();
}

const handleSearch = (value) => {
  console.log(value)
  processDefinitionApi.options({ name: value }).then(res => {
    options.value = res.data.map(item => {
      return {
        value: item.key,
        label: item.name
      }
    })
  })
};
const handleChange = (value) => {
  queryForm.processDefinitionKey = value;
  console.log(value)
}

// 查询方法
const search = async () => {
  setLoading(true);
  try {
    const res = await processInstanceApi.getList({
      ...queryForm,
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
    });
    tableData.value = res.data.records;
    pagination.total = res.data.total;
  } catch (error) {
    Message.error(error.message || '获取列表失败');
  } finally {
    setLoading(false);
  }
};

// 选择变化
const onSelectionChange = (selection) => {
  selectedKeys.value = selection;
};

// 分页变化
const onPageChange = (page) => {
  pagination.current = page;
  search();
};

const handleView = async (record) => {
  processDefinitionApi.getXml(record.processDefinition.id)
    .then(res => {
      highlightActiveNodes.value = [record.activityId];
      data.value = res.data;
      versionTag.value = record.processDefinition.version;
      previewVisible.value = true;
    })
};


const handleActive = async (record) => {
  processInstanceApi.activate(record.id).then(() => {
    record.suspensionState = 1
    Message.success(t('common.operateSuccess'));
  })
}

const handleSuspend = async (record) => {
  processInstanceApi.suspend(record.id).then(() => {
    record.suspensionState = 2
    Message.success(t('common.operateSuccess'));
  })
}

// 删除
const handleDelete = async (record) => {
  try {
    await processInstanceApi.delete(record.id);
    Message.success(t('common.operateSuccess'));
    search();
  } catch (error) {
    Message.error(t('common.deleteFailed'));
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedKeys.value.length === 0) {
    Message.warning(t('common.chooseDeleteItem'));
    return;
  }
  try {
    await processInstanceApi.batchDelete(selectedKeys.value);
    Message.success(t('common.operateSuccess'));
    selectedKeys.value = [];
    search();
  } catch (error) {
    Message.error(t('common.deleteFailed'));
  }
};

// 清空查询条件
const clear = () => {
  formRef.value.resetFields()
  search();
}


onMounted(() => {
  search();
})

</script>

<style lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.query-form {
  background-color: var(--color-bg-2);
  border-radius: 2px;
  margin-bottom: 16px;

  :deep(.arco-form-item) {
    margin-bottom: 16px;
  }

  .arco-btn-group {
    margin-top: 4px;
  }
}

.table-footer {
  display: flex;
  justify-content: end;
  align-items: center;
  padding: 8px 0;
}

.bpmn-viewer {
  height: 600px;
  width: 100%;
}

:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}
</style>